<template>
  <el-upload
    action="https://www.hejiu.ren:9999/api/private/v1/upload"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :headers="headerObj"
    :on-success="handleSuccess"
    list-type="picture"
  >
    <el-button size="small" type="primary">点击上传</el-button>
  </el-upload>
  <el-dialog
    title="图片预览"
    v-model="centerDialogVisible"
    width="50%"
    destroy-on-close
    center>
    <img :src="fileURL" alt="jpg" class="w-100" style="height: 500px">
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import { useStore } from '@/store'
import { MessageFunc } from '@/utils/ElMessageFunc'
import { PiceListProps } from '@/store/storeType'

// 上传组件逻辑
const UploadFn = () => {
  const fileURL = ref('') //上传图片地址
  const centerDialogVisible = ref(false)
  const store = useStore()
  const token = localStorage.getItem('token')
  const headerObj = { // 请求头
    authorization: token
  }
  const handleSuccess = (response: any) => {
    if (response.meta.status === 403) MessageFunc('error', response.meta.msg)
    if (response.meta.status !== 200) MessageFunc('error', '图片上传失败')
    if (store.state.productList.redactModule.redactData.pics) {
      store.state.productList.redactModule.redactData.pics.push({"pic": response.data.tmp_path})
      MessageFunc('success', '图片上传成功')
    }
  }
  // 删除上传图片并且更新删除后的图片url地址数组
  const handleRemove = (file: any) => {
    const removeFileUrl = file.response.data.tmp_path
    const picsNewArr = store.state.productList.redactModule.redactData.pics?.map((item: any) => {
      if (item.pic !== removeFileUrl) return item
    })
    if (store.state.productList.redactModule.redactData.pics && picsNewArr) {
      store.state.productList.redactModule.redactData.pics = picsNewArr as PiceListProps[]
    }
  }

  // 更新上传图片地址
  const handlePreview = (file: any) => {
    fileURL.value = file.response.data.url
    centerDialogVisible.value = true
  }
  return { handleSuccess, handleRemove, handlePreview, centerDialogVisible, fileURL, headerObj }
}

export default defineComponent({
  name: 'XUpload',
  setup() {
    const { handleSuccess, handleRemove, handlePreview, centerDialogVisible, fileURL, headerObj } = UploadFn()
    return { handleSuccess, handleRemove, handlePreview, centerDialogVisible, fileURL, headerObj }
  },
})
</script>
